package com.bupt.interceptor;




import com.bupt.annotation.LoginRequired;
import com.bupt.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;


/**
 * 对于未登录的其他请求进行拦截
 */
@Configuration
@Slf4j
public class SessionInterceptor implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SecurityInterceptor())
                //不拦截swagger
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**","/swagger-ui.html")
                //拦截其他所有
                .addPathPatterns("/**");
    }
    //设置不拦截swagger
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**").allowedOrigins("*")
//                .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
//                .allowCredentials(true)
////                .maxAge(3600)
//        ;
//    }


}

@Configuration
@Slf4j
class SecurityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        System.out.println("进入拦截器");
        //避免handler强转错误
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            //判断登录注解是否存在
            if (method.isAnnotationPresent(LoginRequired.class)){
                HttpSession session = request.getSession();
                //验证当前session是否存在，存在返回true true代表能正常处理业务逻辑
                if (session.getAttribute(session.getId()) != null){
                    log.info("session拦截器，session={}，验证通过",session.getId());
                    return true;
                }
                //session不存在，返回false，并提示请重新登录。
                log.info("{} ,session拦截器，session={}，验证失败",request.getRequestURI(),session.getId());
                //web拦截器貌似不会被统一格式接口处理，所以要自己手动处理
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().print(
                        "{\"status\":"+ ResultCode.USER_NOT_LOGIN.code()+"," +
                                "\"desc\":\""+ResultCode.USER_NOT_LOGIN.message()+"\"," +
                                "\"data\":null}"
                );
                return false;
            }
        }

//        //设置跨域session报错的问题
//        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
//        response.addHeader("Access-Control-Allow-Methods", "*");
//        response.addHeader("Access-Control-Allow-Headers", "Accept,Authorization,DNT,Content-Type,Referer,User-Agent");
//        response.addHeader("Access-Control-Allow-Credentials","true"); // 允许携带验证信息
        return true;

    }
}

